package com.city.dispatch.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.model.AMapCalcRouteResult;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapModelCross;
import com.amap.api.navi.model.AMapNaviCameraInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviRouteNotifyData;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AMapServiceAreaInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.city.dispatch.base.BaseApplication;
import com.city.dispatch.core.widget.CustomDialog;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.city.dispatch.R;
import com.city.dispatch.core.common.HttpHelper;
import com.city.dispatch.core.common.SharedPreferencesUrls;
import com.city.dispatch.core.common.UIHelper;
import com.city.dispatch.core.common.Urls;
import com.city.dispatch.core.widget.LoadingDialog;
import com.city.dispatch.model.GPSTrackBean;
import com.city.dispatch.model.ResultConsel;
import com.city.dispatch.swipebacklayout.app.SwipeBackActivity;
import com.city.dispatch.utils.LogUtil;
import com.city.dispatch.utils.ToastUtil;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/10/18 0018.
 */

public class MerchantAddressMapActivity extends SwipeBackActivity implements View.OnClickListener, LocationSource, AMapLocationListener, AMapNaviListener, AMap.OnCameraChangeListener {

    @BindView(R.id.mainUI_title_backBtn)
    ImageView backBtn;
//    @BindView(R.id.mainUI_title_rightBtn)
//    TextView rightBtn;
//    @BindView(R.id.mainUI_title_titleText)
//    TextView titleText;
    @BindView(R.id.ui_merchantAddress_map)
    MapView mapView;
    @BindView(R.id.et_name)
    EditText codeNumEdit;
    @BindView(R.id.searchBtn)
    ImageView searchBtn;
    @BindView(R.id.tv_day)
    TextView tv_day;
    @BindView(R.id.ll_car_search)
    LinearLayout ll_car_search;

    private Context context;
//    private LoadingDialog loadingDialog;

    private double latitude;
    private double longitude;
    private AMap aMap;
    private static final int STROKE_COLOR = Color.argb(80, 3, 0, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    private LatLng myLocation = null;
    private Marker centerMarker;
    private BitmapDescriptor successDescripter;
    private BitmapDescriptor bikeDescripter;
    private BitmapDescriptor originDescripter;
    private BitmapDescriptor terminusDescripter;

    private Polyline polyline;
    private PolylineOptions mPolyoptions;

    private Marker originMarker;
    private Marker terminusMarker;

    private String begintime;
    private String endtime;

    private String type;

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    private int carmodel_id;
    private String codenum;

    float leveltemp = 18f;

    private AMapNavi mAMapNavi;
    private RouteOverLay routeOverLay;

    public static double referLatitude = 0.0;
    public static double referLongitude = 0.0;

    protected OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    private boolean mFirstFix = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_merchant_address_map);
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        context = this;
//        latitude = Double.parseDouble(getIntent().getExtras().getString("latitude"));
//        longitude = Double.parseDouble(getIntent().getExtras().getString("longitude"));

        carmodel_id = getIntent().getIntExtra("carmodel_id", 0);
        codenum = getIntent().getStringExtra("codenum");

        codenum = codenum==null?"":codenum;


        init();
    }

    private void init(){

        Date date=new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
//        date=calendar.getTime(); //这个时间就是日期往后推一天的结果

        begintime = formatter.format(date);
        endtime = formatter.format(calendar.getTime());

//        tv_day.setText("日期范围："+begintime+" 到 "+endtime);

//        titleText.setText("车辆位置");
//        rightBtn.setText("选择日期");
        loadingDialog = new LoadingDialog(context);
        loadingDialog.setCancelable(false);
        loadingDialog.setCanceledOnTouchOutside(false);
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);// 设置地图logo显示在右下方
        aMap.getUiSettings().setLogoBottomMargin(-100);

        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(leveltemp);// 设置缩放监听
        successDescripter = BitmapDescriptorFactory.fromResource(R.drawable.icon_usecarnow_position_succeed);
        bikeDescripter = BitmapDescriptorFactory.fromResource(R.drawable.bike_icon);
        originDescripter = BitmapDescriptorFactory.fromResource(R.drawable.origin_icon);
        terminusDescripter = BitmapDescriptorFactory.fromResource(R.drawable.terminus_icon);
        aMap.moveCamera(cameraUpdate);


        mAMapNavi = AMapNavi.getInstance(context);
        mAMapNavi.addAMapNaviListener(this);

        codeNumEdit.setText(codenum);

        if(carmodel_id==2){
            ll_car_search.setVisibility(View.VISIBLE);
        }else{
            ll_car_search.setVisibility(View.GONE);
        }

        backBtn.setOnClickListener(this);
//        rightBtn.setOnClickListener(this);
        searchBtn.setOnClickListener(this);
        ll_car_search.setOnClickListener(this);


        codenum = codeNumEdit.getText().toString().trim();
        if (codenum != null && !"".equals(codenum)){
            initHttp();
        }


    }

    private void initHttp() {
//        String uid = SharedPreferencesUrls.getInstance().getString("uid","");
        String access_token = SharedPreferencesUrls.getInstance().getString("access_token","");
        if (access_token == null || "".equals(access_token)){
            Toast.makeText(context,"请先登录您的账号",Toast.LENGTH_SHORT).show();
            UIHelper.goToAct(context,LoginActivity.class);
            return;
        }
//        RequestParams params = new RequestParams();
//        params.put("codenum",codenum);
        HttpHelper.get(context, Urls.car+codenum, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                onStartCommon("正在加载");
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                onFailureCommon(throwable.toString());
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, final String responseString) {
                m_myHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        LogUtil.e("mama===car","==="+responseString);
                        try {
                            ResultConsel result = JSON.parseObject(responseString, ResultConsel.class);

                            if(result.getStatus_code()==0){
                                JSONObject jsonObject = new JSONObject(result.getData());

                                if("".equals(jsonObject.getString("latitude"))){
                                    myLocation = new LatLng(31.76446, 119.920594);  //latitude:31.76446,    longitude:119.920594
                                    mAMapNavi.calculateRideRoute(new NaviLatLng(referLatitude, referLongitude), new NaviLatLng(31.76446, 119.920594));
                                }else{
                                    myLocation = new LatLng(Double.parseDouble(jsonObject.getString("latitude")), Double.parseDouble(jsonObject.getString("longitude")));
                                    mAMapNavi.calculateRideRoute(new NaviLatLng(referLatitude, referLongitude), new NaviLatLng(Double.parseDouble(jsonObject.getString("latitude")), Double.parseDouble(jsonObject.getString("longitude"))));
//                                    mAMapNavi.calculateWalkRoute(new NaviLatLng(referLatitude, referLongitude), new NaviLatLng(Double.parseDouble(jsonObject.getString("latitude")), Double.parseDouble(jsonObject.getString("longitude"))));
                                }
                                addChooseMarker();
//                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, leveltemp));

//                                markerPosition = marker.getPosition();

//                                codenum = jsonObject.getString("number");
                                carmodel_id = jsonObject.getInt("carmodel_id");

                                if(carmodel_id==2){
                                    ll_car_search.setVisibility(View.VISIBLE);
                                }else{
                                    ll_car_search.setVisibility(View.GONE);
                                }

                            }else{

                                ToastUtil.showMessageApp(context, result.getMessage());
                                if(centerMarker!=null){
                                    centerMarker.remove();
                                    centerMarker = null;
                                }

                                if(routeOverLay != null){
                                    routeOverLay.removeFromMap();
                                }
                            }


//                            if (result.getFlag().equals("Success")){
//                                JSONObject jsonObject = new JSONObject(result.getData());
//                                if (!"[]".equals(result.getData())){
//
//                                    type = jsonObject.getString("type");
//
//                                    if("4".equals(type) || "7".equals(type)){
//                                        gpstrack(codenum);
//                                    }else{
//                                        tv_day.setText("");
//
//                                        myLocation = new LatLng(Double.parseDouble(jsonObject.getString("latitude")), Double.parseDouble(jsonObject.getString("longitude")));
//                                        addChooseMarker();
//                                        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 16));
//                                    }
//
//                                }
//                            } else {
//                                Toast.makeText(context,result.getMsg(),Toast.LENGTH_SHORT).show();
//                            }
                        } catch (Exception e) {
                            LogUtil.e("Test","异常:"+e);
                        }
                        if (loadingDialog != null && loadingDialog.isShowing()){
                            loadingDialog.dismiss();
                        }
                    }
                });

            }
        });
    }

    private void gpstrack(String codenum){

        final String uid = SharedPreferencesUrls.getInstance().getString("uid","");
        final String access_token = SharedPreferencesUrls.getInstance().getString("access_token","");
        if (uid == null || "".equals(uid) || access_token == null || "".equals(access_token)){
            ToastUtil.showMessageApp(context,"请先登录账号");
            UIHelper.goToAct(context, LoginActivity.class);
        }else {

//            if (begintime == null || "".equals(begintime)){
//                Toast.makeText(context,"请选择日期",Toast.LENGTH_SHORT).show();
//                return;
//            }
//
//            if (endtime == null || "".equals(endtime)){
//                Toast.makeText(context,"请选择日期",Toast.LENGTH_SHORT).show();
//                return;
//            }
//
//            tv_day.setText("日期范围："+begintime+" 到 "+endtime);

            if (polyline != null) {
                polyline.remove();
                polyline = null;
            }

            if(originMarker!=null){
                originMarker.remove();
            }

            if(terminusMarker!=null){
                terminusMarker.remove();
            }

            mPolyoptions = new PolylineOptions();
            mPolyoptions.width(40f);
            mPolyoptions.setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.grasp_trace_line));

            RequestParams params = new RequestParams();
            params.put("uid", uid);
            params.put("access_token", access_token);
            params.put("tokencode", codenum);        //80001819、80002041
            params.put("begintime", begintime);
            params.put("endtime", endtime);
            HttpHelper.get(context, Urls.gpstrack, params, new TextHttpResponseHandler() {
                @Override
                public void onStart() {
                    onStartCommon("正在加载");
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    onFailureCommon(throwable.toString());
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, final String responseString) {
                    m_myHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ResultConsel result = JSON.parseObject(responseString, ResultConsel.class);
                                if (result.getFlag().equals("Success")) {
                                    JSONArray array = new JSONArray(result.getData());

                                    LogUtil.e("gpstrack===","==="+responseString);

//                            for (Marker marker : bikeMarkerList){
//                                if (marker != null){
//                                    marker.remove();
//                                }
//                            }
//                            if (!bikeMarkerList.isEmpty() || 0 != bikeMarkerList.size()){
//                                bikeMarkerList.clear();
//                            }
                                    if (0 == array.length()){
                                        ToastUtil.showMessageApp(context, "没有轨迹");
                                    }else {
                                        for (int i = 0; i < array.length(); i++){
                                            GPSTrackBean bean = JSON.parseObject(array.getJSONObject(i).toString(), GPSTrackBean.class);
                                            // 加入自定义标签

                                            LatLng latLng = new LatLng(Double.parseDouble(bean.getLat()),Double.parseDouble(bean.getLon()));

                                            if(i==0){
                                                MarkerOptions bikeMarkerOption = new MarkerOptions().position(latLng).icon(originDescripter);
                                                originMarker = aMap.addMarker(bikeMarkerOption);

                                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
                                            }else if(i==array.length()-1){
                                                MarkerOptions bikeMarkerOption = new MarkerOptions().position(latLng).icon(terminusDescripter);
                                                terminusMarker = aMap.addMarker(bikeMarkerOption);
                                            }else{
//                                        MarkerOptions bikeMarkerOption = new MarkerOptions().position(latLng).icon(bikeDescripter);
//                                        Marker bikeMarker = aMap.addMarker(bikeMarkerOption);
                                            }


                                            mPolyoptions.add(latLng);

                                            LogUtil.e("gpstrack===",polyline+"==="+mPolyoptions.getPoints().size());

                                            if (mPolyoptions.getPoints().size() > 1) {
                                                if (polyline != null) {
                                                    polyline.setPoints(mPolyoptions.getPoints());
                                                } else {
                                                    polyline = aMap.addPolyline(mPolyoptions);
                                                }
//                                        polyline = aMap.addPolyline(mPolyoptions);
                                            }

//                                    bikeMarkerList.add(bikeMarker);
                                        }
                                    }
                                } else {
                                    ToastUtil.showMessageApp(context,result.getMsg());
                                }
                            } catch (Exception e) {

                            }
                            if (loadingDialog != null && loadingDialog.isShowing()){
                                loadingDialog.dismiss();
                            }
                        }
                    });

                }
            });
        }

    }

    protected Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {
                case 0:
                    break;
                default:
                    break;
            }
            return false;
        }
    });


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mainUI_title_backBtn:
                scrollToFinishActivity();
                break;
            case R.id.mainUI_title_rightBtn:
                Intent intent = new Intent(context, HistoryRoadFiltateActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent,0);
                break;
            case R.id.searchBtn:
                codenum = codeNumEdit.getText().toString().trim();
                if (codenum == null || "".equals(codenum)){
                    Toast.makeText(context,"请输入车辆编号",Toast.LENGTH_SHORT).show();
                    return;
                }

                initHttp();
                break;

            case R.id.ll_car_search:
                ddSearch();
                break;

            default:
                break;
        }
    }

    private void ddSearch(){
        LogUtil.e("ddSearch===", "==="+codenum);

        String access_token = SharedPreferencesUrls.getInstance().getString("access_token","");
        if (access_token == null || "".equals(access_token)){
            Toast.makeText(context,"请先登录账号",Toast.LENGTH_SHORT).show();
            UIHelper.goToAct(context, LoginActivity.class);
        }else {
//            RequestParams params = new RequestParams();
//            params.put("tokencode",codenum);
            HttpHelper.post(context, Urls.search+codenum, null, new TextHttpResponseHandler() {
                @Override
                public void onStart() {
                    if (loadingDialog != null && !loadingDialog.isShowing()) {
                        loadingDialog.setTitle("正在提交");
                        loadingDialog.show();
                    }
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    if (loadingDialog != null && loadingDialog.isShowing()){
                        loadingDialog.dismiss();
                    }
                    UIHelper.ToastError(context, throwable.toString());
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    try {
                        LogUtil.e("ddSearch===1", "==="+responseString);

                        ResultConsel result = JSON.parseObject(responseString, ResultConsel.class);

//                        if(result.getStatus_code()==200){
//                            curMarker.setIcon(bikeDescripter_blue);
//                        }else{
//
//                        }

                        Toast.makeText(context, result.getMessage(), Toast.LENGTH_SHORT).show();

//                        if (result.getFlag().equals("Success")) {
//                            Toast.makeText(context,"发送寻车指令成功",Toast.LENGTH_SHORT).show();
//                        }else {
//                            Toast.makeText(context,result.getMsg(),Toast.LENGTH_SHORT).show();
//                        }
                    } catch (Exception e) {
                    }
                    if (loadingDialog != null && loadingDialog.isShowing()){
                        loadingDialog.dismiss();
                    }
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data != null) {
                    begintime = data.getExtras().getString("starttime");
                    endtime = data.getExtras().getString("endtime");

                    tv_day.setText("日期范围："+begintime+" 到 "+endtime);

                    LogUtil.e("onActivityResult===",begintime+"==="+endtime);

                    codenum = codeNumEdit.getText().toString().trim();
                    if (codenum == null || "".equals(codenum)){
                        Toast.makeText(context,"请输入车辆编号",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    initHttp();
                }
                break;

            default:
                break;
        }
    }

    private void setUpMap2() {
//        aMap.setLocationSource(this);// 设置定位监听
//        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
//        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
//        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
//        aMap.setLoadOfflineData(true);

        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);


        final String STYLE_NAME = "style.data";
        final String STYLE_EXTRA_NAME = "style_extra.data";


        final String filePath = context.getFilesDir().getAbsolutePath() + "/" + STYLE_NAME;
        final String filePathExtra = context.getFilesDir().getAbsolutePath() + "/" + STYLE_EXTRA_NAME;
        final File file = new File(filePath);
        final File fileExtra = new File(filePathExtra);

        LogUtil.e("setUpMap===000", context.getAssets()+"==="+file+"==="+file.exists()+"==="+fileExtra.exists());

        if (file.exists()) {
//            aMap.setCustomMapStyle(
//                    new com.amap.api.maps.model.CustomMapStyleOptions()
//                            .setEnable(true)
//                            .setStyleDataPath(filePath)
//                            .setStyleExtraPath(filePathExtra)
//            );
//            return;//本地已有，不再下载
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            LogUtil.e("setUpMap===00", context.getAssets()+"==="+inputStream);

            inputStream = context.getAssets().open(STYLE_NAME);

            LogUtil.e("setUpMap===0", context.getAssets()+"==="+inputStream);

            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);
            outputStream = new FileOutputStream(file);
            outputStream.write(b);

//                    String filePath = context.getFilesDir().getAbsolutePath() + "/" + STYLE_NAME;

//                    aMap.setCustomMapStylePath(filePath);
//                    aMap.setMapCustomEnable(true);
//                    aMap.showMapText(true);

            LogUtil.e("setUpMap===", "==="+filePath);

//            aMap.setCustomMapStyle(
//                    new com.amap.api.maps.model.CustomMapStyleOptions()
//                            .setEnable(true)
//                            .setStyleDataPath(filePath)
////                                    .setStyleExtraPath(filePath)
////                                    .setStyleId("1b319281566f48d9ce57449b30be3b6e")//官网控制台-自定义样式 获取
//
////                                    .setStyleExtraPath("/mnt/sdcard/amap/style_extra.data")
////                                    .setStyleTexturePath("/mnt/sdcard/amap/textures.zip")
//            );

        } catch (Exception e) {
            e.printStackTrace();
//            closeLoadingDialog();
            LogUtil.e("setUpMap===e", context.getAssets()+"==="+e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        if (fileExtra.exists()) {
//            aMap.setCustomMapStyle(
//                    new com.amap.api.maps.model.CustomMapStyleOptions()
//                            .setEnable(true)
//                            .setStyleDataPath(filePath)
//                            .setStyleExtraPath(filePathExtra)
//            );
//            return;//本地已有，不再下载
            fileExtra.delete();
        }
        try {
            fileExtra.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        outputStream = null;
        inputStream = null;
        try {
            LogUtil.e("setUpMap===100", context.getAssets()+"==="+inputStream);

            inputStream = context.getAssets().open(STYLE_EXTRA_NAME);

            LogUtil.e("setUpMap===10", context.getAssets()+"==="+inputStream);

            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);
            outputStream = new FileOutputStream(fileExtra);
            outputStream.write(b);

//                    String filePath = context.getFilesDir().getAbsolutePath() + "/" + STYLE_NAME;

//                    aMap.setCustomMapStylePath(filePath);
//                    aMap.setMapCustomEnable(true);
//                    aMap.showMapText(true);

            LogUtil.e("setUpMap===1", "==="+filePathExtra);

            aMap.setCustomMapStyle(
                    new com.amap.api.maps.model.CustomMapStyleOptions()
                            .setEnable(true)
                            .setStyleDataPath(filePath)
                            .setStyleExtraPath(filePathExtra)
//                                    .setStyleId("1b319281566f48d9ce57449b30be3b6e")//官网控制台-自定义样式 获取
//                                    .setStyleExtraPath("/mnt/sdcard/amap/style_extra.data")
//                                    .setStyleTexturePath("/mnt/sdcard/amap/textures.zip")
            );

        } catch (Exception e) {
            e.printStackTrace();
//            closeLoadingDialog();
            LogUtil.e("setUpMap===1e", context.getAssets()+"==="+e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//        }).start();



        LogUtil.e("setUpMap===2", "==="+context.getFilesDir().getAbsolutePath());


    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        setupLocationStyle();

        LogUtil.e("setUpMap===", context.getAssets()+"==="+getFilesDir().getAbsolutePath());

        final String STYLE_NAME = "style.data";
        final String STYLE_EXTRA_NAME = "style_extra.data";

        final String filePath = context.getFilesDir().getAbsolutePath() + "/" + STYLE_NAME;
        final String filePathExtra = context.getFilesDir().getAbsolutePath() + "/" + STYLE_EXTRA_NAME;
        final File file = new File(filePath);
        final File fileExtra = new File(filePathExtra);

        LogUtil.e("setUpMap===000", context.getAssets()+"==="+file+"==="+file.exists()+"==="+fileExtra.exists());

        if (file.exists()) {
//            aMap.setCustomMapStyle(
//                    new com.amap.api.maps.model.CustomMapStyleOptions()
//                            .setEnable(true)
//                            .setStyleDataPath(filePath)
//                            .setStyleExtraPath(filePathExtra)
//            );
//            return;//本地已有，不再下载
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            LogUtil.e("setUpMap===00", context.getAssets()+"==="+inputStream);

            inputStream = context.getAssets().open(STYLE_NAME);

            LogUtil.e("setUpMap===0", context.getAssets()+"==="+inputStream);

            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);
            outputStream = new FileOutputStream(file);
            outputStream.write(b);

//                    String filePath = context.getFilesDir().getAbsolutePath() + "/" + STYLE_NAME;

//                    aMap.setCustomMapStylePath(filePath);
//                    aMap.setMapCustomEnable(true);
//                    aMap.showMapText(true);

            LogUtil.e("setUpMap===", "==="+filePath);

//            aMap.setCustomMapStyle(
//                    new com.amap.api.maps.model.CustomMapStyleOptions()
//                            .setEnable(true)
//                            .setStyleDataPath(filePath)
////                                    .setStyleExtraPath(filePath)
////                                    .setStyleId("1b319281566f48d9ce57449b30be3b6e")//官网控制台-自定义样式 获取
//
////                                    .setStyleExtraPath("/mnt/sdcard/amap/style_extra.data")
////                                    .setStyleTexturePath("/mnt/sdcard/amap/textures.zip")
//            );

        } catch (Exception e) {
            e.printStackTrace();
//            closeLoadingDialog();
            LogUtil.e("setUpMap===e", context.getAssets()+"==="+e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        if (fileExtra.exists()) {
//            aMap.setCustomMapStyle(
//                    new com.amap.api.maps.model.CustomMapStyleOptions()
//                            .setEnable(true)
//                            .setStyleDataPath(filePath)
//                            .setStyleExtraPath(filePathExtra)
//            );
//            return;//本地已有，不再下载
            fileExtra.delete();
        }
        try {
            fileExtra.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        outputStream = null;
        inputStream = null;
        try {
            LogUtil.e("setUpMap===100", context.getAssets()+"==="+inputStream);

            inputStream = context.getAssets().open(STYLE_EXTRA_NAME);

            LogUtil.e("setUpMap===10", context.getAssets()+"==="+inputStream);

            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);
            outputStream = new FileOutputStream(fileExtra);
            outputStream.write(b);

//                    String filePath = context.getFilesDir().getAbsolutePath() + "/" + STYLE_NAME;

//                    aMap.setCustomMapStylePath(filePath);
//                    aMap.setMapCustomEnable(true);
//                    aMap.showMapText(true);

            LogUtil.e("setUpMap===1", "==="+filePathExtra);

            aMap.setCustomMapStyle(
                    new com.amap.api.maps.model.CustomMapStyleOptions()
                            .setEnable(true)
                            .setStyleDataPath(filePath)
                            .setStyleExtraPath(filePathExtra)
//                                    .setStyleId("1b319281566f48d9ce57449b30be3b6e")//官网控制台-自定义样式 获取
//                                    .setStyleExtraPath("/mnt/sdcard/amap/style_extra.data")
//                                    .setStyleTexturePath("/mnt/sdcard/amap/textures.zip")
            );

        } catch (Exception e) {
            e.printStackTrace();
//            closeLoadingDialog();
            LogUtil.e("setUpMap===1e", context.getAssets()+"==="+e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置自定义定位蓝点
     */
    private void setupLocationStyle() {
//        // 自定义系统定位蓝点
//        MyLocationStyle myLocationStyle = new MyLocationStyle();
//        // 自定义定位蓝点图标
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked));
//        // 自定义精度范围的圆形边框颜色
//        myLocationStyle.strokeColor(STROKE_COLOR);
//        //自定义精度范围的圆形边框宽度
//        myLocationStyle.strokeWidth(5);
//        // 设置圆形的填充颜色
//        myLocationStyle.radiusFillColor(FILL_COLOR);
//        // 将自定义的 myLocationStyle 对象添加到地图上
//        aMap.setMyLocationStyle(myLocationStyle);

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked));
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次
        aMap.setMyLocationStyle(myLocationStyle);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mapView!=null){
            mapView.onDestroy();
        }

        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }

        ToastUtil.showMessage(context, "mama===onDestroy");

        deactivate();

        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }


    private void addSelfMarker() {
        // 加入自定义标签

        Log.e("addSelfMarker===0", "==="+centerMarker);

//        if(centerMarker == null){
//
//            View view = View.inflate(context, R.layout.marker_info_layout, null);
//            iv_marker = view.findViewById(R.id.iv);
//            iv_marker.setImageResource(R.drawable.marker1);
//            tv_car_count = view.findViewById(R.id.tv_car_count);
//            tv_car_count.setText((car_count>99?99:car_count)+"辆");
//            centerMarkerOption = new MarkerOptions().position(myLocation).icon(BitmapDescriptorFactory.fromView(view));
//
//            Log.e("addChooseMarker===", "==="+myLocation);
//
//            centerMarker = aMap.addMarker(centerMarkerOption);
//            centerMarker.setDraggable(true);
//
//
//        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                    CameraUpdate update = CameraUpdateFactory.changeLatLng(myLocation);
//                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(myLocation));
                CameraUpdate update = CameraUpdateFactory.zoomTo(18f);
                aMap.animateCamera(update, 1000, new AMap.CancelableCallback() {
                    @Override
                    public void onFinish() {
                        aMap.setOnCameraChangeListener(MerchantAddressMapActivity.this);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
            }
        }, 1000);

    }

    private void addChooseMarker() {
        // 加入自定义标签

        if(centerMarker==null){
            MarkerOptions centerMarkerOption = new MarkerOptions().position(myLocation).icon(successDescripter);
            centerMarker = aMap.addMarker(centerMarkerOption);
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    CameraUpdate update = CameraUpdateFactory.zoomTo(leveltemp);
//                    aMap.animateCamera(update, 1000, new AMap.CancelableCallback() {
//                        @Override
//                        public void onFinish() {
//                        }
//
//                        @Override
//                        public void onCancel() {
//
//                        }
//                    });
//                }
//            }, 1000);
        }else{
            centerMarker.setPosition(myLocation);
        }


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            scrollToFinishActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {

            if ((referLatitude == amapLocation.getLatitude()) && (referLongitude == amapLocation.getLongitude())) return;

            Log.e("mama===Changed", amapLocation.getLatitude() + "===" + amapLocation.getLongitude());
            ToastUtil.showMessage(context, amapLocation.getLatitude() + "===" + amapLocation.getLongitude());

            if (amapLocation != null && amapLocation.getErrorCode() == 0) {

                if (0.0 != amapLocation.getLatitude() && 0.0 != amapLocation.getLongitude()) {
                    String latitude = SharedPreferencesUrls.getInstance().getString("biking_latitude", "");
                    String longitude = SharedPreferencesUrls.getInstance().getString("biking_longitude", "");

                    if (mListener != null) {
                        mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                    }

                    referLatitude = amapLocation.getLatitude();
                    referLongitude = amapLocation.getLongitude();
//                    myLocation = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());

//                    Log.e("main===Changed>>>0", referLatitude+"==="+referLongitude+"》》》"+mFirstFix);

                    if (mFirstFix) {
                        mFirstFix = false;

//                        addSelfMarker();

//                        initNearby(amapLocation.getLatitude(), amapLocation.getLongitude());
//                        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 16));
//
//                        accuracy = amapLocation.getAccuracy();
//
//                        addChooseMarker();
//                        addCircle(myLocation, amapLocation.getAccuracy());
                    }
//                    else {
//
//                        if (!isContainsList.isEmpty() || 0 != isContainsList.size()) {
//                            isContainsList.clear();
//                        }
//                        for (int i = 0; i < pOptions.size(); i++) {
//                            isContainsList.add(pOptions.get(i).contains(myLocation));
//                        }
//                    }
//
//                    ToastUtil.showMessage(context, isContainsList.contains(true) + "======" + near);
//
//                    if ((isContainsList.contains(true) || macList.size() > 0) && !"1".equals(type)) {
//                        near = 0;
//                    } else {
//                        near = 1;
//                    }

                } else {
                    CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
                    customBuilder.setTitle("温馨提示").setMessage("您需要在设置里打开位置权限！")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    finish();
                                }
                            }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
//                            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_ASK_PERMISSIONS);
                        }
                    });
                    customBuilder.create().show();
                }

//                //保存经纬度到本地
//                SharedPreferencesUrls.getInstance().putString("latitude", "" + amapLocation.getLatitude());
//                SharedPreferencesUrls.getInstance().putString("longitude", "" + amapLocation.getLongitude());
            }


        }
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
//	    super.activate(listener);

        mListener = listener;

        LogUtil.e("mama===activate", "===" + mlocationClient);


        if (mlocationClient != null) {

            mlocationClient.setLocationListener(this);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(2 * 1000);
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();

//			mListener.onLocationChanged(amapLocation);
        }

//		if (mListener != null) {
//			mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
//		}

        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(context);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

            // 关闭缓存机制
            mLocationOption.setLocationCacheEnable(false);

            //设置是否只定位一次,默认为false
            mLocationOption.setOnceLocation(false);
            //设置是否强制刷新WIFI，默认为强制刷新
            mLocationOption.setWifiActiveScan(true);
            //设置是否允许模拟位置,默认为false，不允许模拟位置
            mLocationOption.setMockEnable(false);

            mLocationOption.setInterval(2 * 1000);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    @Override
    public void onInitNaviFailure() {

    }

    @Override
    public void onInitNaviSuccess() {

    }

    @Override
    public void onStartNavi(int i) {

    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {

    }

    @Override
    public void onGetNavigationText(int i, String s) {

    }

    @Override
    public void onGetNavigationText(String s) {

    }

    @Override
    public void onEndEmulatorNavi() {

    }

    @Override
    public void onArriveDestination() {

    }

    @Override
    public void onCalculateRouteFailure(int i) {

    }

    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {

    }


    @Override
    public void updateCameraInfo(AMapNaviCameraInfo[] aMapNaviCameraInfos) {

    }

    @Override
    public void updateIntervalCameraInfo(AMapNaviCameraInfo aMapNaviCameraInfo, AMapNaviCameraInfo aMapNaviCameraInfo1, int i) {

    }

    @Override
    public void onServiceAreaUpdate(AMapServiceAreaInfo[] aMapServiceAreaInfos) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showModeCross(AMapModelCross aMapModelCross) {

    }

    @Override
    public void hideModeCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo aMapLaneInfo) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateRouteSuccess(int[] ints) {
        LogUtil.e("onCalculateRouteSuc=", "==="+routeOverLay);

//        routeOverlays.clear();
//        ways.clear();

        if(routeOverLay != null){
            routeOverLay.removeFromMap();
        }

//        mAMapNavi.startNavi(NaviType.EMULATOR);

        AMapNaviPath path = mAMapNavi.getNaviPath();

        drawRoutes(-1, path);
    }


    private void drawRoutes(int routeId, AMapNaviPath path) {

//        calculateSuccess = true;
        aMap.moveCamera(CameraUpdateFactory.changeTilt(0));
        //路径绘制图层
        routeOverLay = new RouteOverLay(aMap, path, context);
        routeOverLay.setTrafficLine(false);
        routeOverLay.setStartPointBitmap(null);
        routeOverLay.setEndPointBitmap(null);
        routeOverLay.addToMap();

        LogUtil.e("drawRoutes===", "==="+path.getAllLength());

//        tv_navi_distance.setText(path.getAllLength()+"米");

        LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();//存放所有点的经纬度

//                for(int i=0;i<markers.size();i++){
//                    boundsBuilder.include(markers.get(i).getPosition());//把所有点都include进去（LatLng类型）
//                }

        boundsBuilder.include(new LatLng(referLatitude, referLongitude));
        boundsBuilder.include(myLocation);

//                aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 15));
//                aMap.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(boundsBuilder.build(),10,10,10,10), 0L, null);

        aMap.moveCamera(CameraUpdateFactory.newLatLngBoundsRect(boundsBuilder.build(),100,100,100 * Math.round(BaseApplication.density),100 * Math.round(BaseApplication.density)));    //left_right_padding, left_right_padding, top_padding, bottom_padding


//        routeOverlays.put(routeId, routeOverLay);
    }

    @Override
    public void notifyParallelRoad(int i) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }


    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {

    }

    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {

    }

    @Override
    public void onPlayRing(int i) {

    }

    @Override
    public void onCalculateRouteSuccess(AMapCalcRouteResult aMapCalcRouteResult) {
        LogUtil.e("onCalculateRouteSuc=@", "==="+routeOverLay);
    }

    @Override
    public void onCalculateRouteFailure(AMapCalcRouteResult aMapCalcRouteResult) {

    }

    @Override
    public void onNaviRouteNotify(AMapNaviRouteNotifyData aMapNaviRouteNotifyData) {

    }

    @Override
    public void onGpsSignalWeak(boolean b) {

    }
}
